import consts from './consts'
import routes from '@/router/routes'
import moduleRoutes from '@/router/module-routes'

export default {
  setToken: function (token) {
    window.localStorage.setItem(consts.USER_TOKEN, token)
  },
  getToken: function() {
    return window.localStorage.getItem(consts.USER_TOKEN)
  },
  removeUserInfo: function() {
    window.localStorage.removeItem(consts.USER_TOKEN)
    window.localStorage.removeItem(consts.USER_BASE_INFO)
    window.localStorage.removeItem(consts.USER_MENU)
    window.localStorage.removeItem(consts.USER_PERM)
  },
  setUser: function(data) {
    if (data) {
      window.localStorage.setItem(consts.USER_BASE_INFO, JSON.stringify(data))
    }
  },
  getUser: function() {
    const str = window.localStorage.getItem(consts.USER_BASE_INFO)
    return str ? JSON.parse(str) : []
  },
  setMenuList: function(data) {
    if (data) {
      window.localStorage.setItem(consts.USER_MENU, JSON.stringify(data))
    }
  },
  getMenuList: function() {
    const str = window.localStorage.getItem(consts.USER_MENU)
    return str ? JSON.parse(str) : []
  },
  setPermissionMap: function(data) {
    if (data) {
      window.localStorage.setItem(consts.USER_PERM, JSON.stringify(data))
    }
  },
  getPermissionMap: function() {
    const str = window.localStorage.getItem(consts.USER_PERM)
    return str ? JSON.parse(str) : []
  },
  hasPerm: function(menuCode, elementCode) {
    const permissionMap = this.getPermissionMap()
    if (permissionMap) {
      const elementList = permissionMap[menuCode]
      return elementList && elementList.indexOf(elementCode) >= 0
    }
    return false
  },
  getClientInfo: function() {
    const os = require('os')
    if (!os) {
      return {}
    }
    const platform = os.platform()
    const hostname = os.hostname()
    const username = os.userInfo ? os.userInfo().username : ''
    let ipv4 = ''
    let mac = ''
    const network = os.networkInterfaces()
    if (network) {
      for (const key in network) {
        if (key.startsWith('en')) {
          for (const en of network[key]) {
            if (en.family.toUpperCase() === 'IPV4') {
              ipv4 = en.address
              mac = en.mac
              break
            }
          }
        }
      }
    }
    return {
      Client_Platform: platform,
      Client_Hostname: hostname,
      Client_Username: username,
      Client_Ipv4: ipv4,
      Client_Mac: mac
    }
  },
  isSupportWebSocket: function () {
    return typeof WebSocket !== 'undefined'
  }
}
